let app=getApp();

const timer= require('../../utils/timer.js');

Page({
    data: {
      isIn: !1,
      userInfo: null,
      days_numb: 0,
      story_numb: 0,
      list: [],
      inTop:false,
      vote_num:0,
      info:'当天',
      default_img:'http://bmobfile.funnyfish.cn/2020/05/11/16555bbe40b88c158056807e57232761.png',
      day:0,
      danmuArr:[],
      daylist:[],
      toplist:[],
    allDanmuArr:[],
    showLength:2,
    newDanmuArr:[],
    imgArr:[],
    danmuCurrentIndex:0,
    barrageTimeout:2e3,
    isMonth:false,
    isDisableBarrage:true,
    isStop:false

    },
    bindViewTap: function() {},
    onLoad: function() {
         wx.showToast({
            title:'加载中...',
            icon:'none'
        })
        var avatarurl=wx.getStorageSync('uimg');
        if(avatarurl){
          let item={avatarurl:avatarurl,Comment:'查看排行榜'}
          this.setData({
            danmuArr:[item]
          })
        }

        this.getList();
        this.getNewUser();
        
    },
    getNewUser(){
      let that=this
        let param = {
          'notlike':{
            k:'avatarurl',
            v:''
          }
        }
        let attr={
          limit:125,
          order:'-updatedAt',
          select:'avatarurl,nickName'
        }
        wx.Als.bmobFunc('vote_user', 'all', param,attr).then(res => {
    
          if (res.length > 0) {
            let arr=app.getRandomArrayElements(res,30)
            that.setData({
              imgArr: arr,
              allDanmuArr:arr
    
            })
            that.barrageScrollMain()
          }
        })
    },
      showMonth(e){
    let type=e.currentTarget.dataset.type
    console.log(type)
    if(type==2){
    var  isMonth= !1
    var info='当天';
       this.setData({
      isMonth: isMonth,
      info:info,
      list:this.data.daylist
    })
    }else{
      var  isMonth= !0
    var info='近期';
    if(this.data.toplist.length==0){
      this.getTopUser()
         this.setData({
      isMonth: isMonth,
      info:info
    })
    }else{
      this.setData({
      isMonth: isMonth,
      info:info,
       list:this.data.toplist
    })
    }
    }
  
  },
  getTopUser(){
 let that=this
 var uid=wx.getStorageSync('uid')
        let param = {
          'notlike':{
            k:'show',
            v:false
          }
        }
        let attr={
          limit:100,
          order:'-vote_num,-createdAt',
          select:'avatarurl,nickName,share_num,vote_num'
        }
        wx.Als.bmobFunc('vote_user', 'all', param,attr).then(res => {
          
          if (res.length > 0) {
            // var arr=res.map(item=>{
            //   return {newvote:(item.vote_num+item.share_num*10),...item}
            // })
            var vote_num=0;
        
            res.forEach(item=>{
              item.newvote=item.vote_num+item.share_num*10;
              if(item.objectId==uid){
                vote_num=item.newvote;
                that.setData({
                   vote_num:vote_num,
                   inTop:true
                })
              }
            })
            
            
            res.sort((a,b)=>{
              return b.newvote-a.newvote
            })
           res=res.splice(0,30)
            that.setData({
              toplist:res,
              list:res,
             
            })
          
         
          }
        })
  },
    onShow(){
             var nickName=wx.getStorageSync('nickName');
          var avatarurl=wx.getStorageSync('uimg')
          var day=wx.getStorageInfoSync(day);
          if(day>0){
             this.setData({
          day:day,
          userInfo:{day:day,nickName:nickName,avatarurl:avatarurl}
        })
          }
       
       
    },
    barrageScrollMain: function() {
    this.data.barrageTimeoutId && clearTimeout(this.data.barrageTimeoutId);
    if(!this.data.isDisableBarrage){return}
    this.data.barrageTimeoutId = setTimeout(function() {
        if (0 != this.data.allDanmuArr.length ) {
            if (!this.data.isStop) {
                var e = this.data.allDanmuArr;
                if (this.data.newDanmuArr.length > 0) {
                    var a;
                    (a = this.data.allDanmuArr).splice.apply(a, [ this.data.danmuCurrentIndex, 0 ].concat(t(this.data.newDanmuArr))), 
                    e = this.data.allDanmuArr, this.data.newDanmuArr = [];
                }
                // let item=app.arrList[this.data.danmuCurrentIndex];
                let arrList=app.arrList;
                let item=arrList[Math.floor(Math.random() * arrList.length)];
                this.data.danmuCurrentIndex >= e.length && this.data.danmuCurrentIndex >= 30 && (this.data.danmuCurrentIndex = 0), 
                this.data.allDanmuArr = e, this.data.danmuArr.push(Object.assign({Comment:item}, e[this.data.danmuCurrentIndex])),
                this.setData({
                    danmuArr: this.data.danmuArr,
                    danmuCurrentIndex: this.data.danmuCurrentIndex + 1
                }, this.barrageScrollMain);
                if(this.data.danmuCurrentIndex>e.length){
                  this.setData({
                
                    allDanmuArr:[],
                    isDisableBarrage:false
                  })
                  clearTimeout(this.data.barrageTimeoutId)
                } 
            }
        } else this.barrageScrollMain();
    }.bind(this), this.data.barrageTimeout);
},
    getList(){
      var that=this
      const query = wx.Bmob.Query("vote_answer");

       query.include('vote_user','userinfo');
       query.order("-createdAt");
        query.select('uid,userinfo');
       query.limit(420);
       var day=timer.getDay(-3);
       var dayinfo=day+" 00:00:00";
        query.equalTo("createdAt", ">", dayinfo);
    
         query.find().then(res => {
          if(res&&res.length>0){
          console.error("ranklist1=")
          var sorted =that.groupBy(res, function (item) {
            return [item.uid];//按照name进行分组
        });
         sorted.sort((a,b)=>{
          return b.length-a.length;
        })
       if(sorted.length>10){
         sorted=sorted.slice(0,10);
        }
      
        that.setData({
          list:sorted,
          daylist:sorted
        })

      }

        });
    
        },
        groupBy(array, f) 
    {
        var that=this;
        const groups = {};
     
        var uid=wx.getStorageSync('uid')  
        var user={uid:uid}
        var newuid=JSON.stringify(f(user));
        var day=0;
        array.forEach(function (o) { //注意这里必须是forEach 大写
          

            if(o.userinfo==undefined||!o.userinfo.nickName==undefined){
            
              o.userinfo={
                nickName:"匿名",
                avatarurl:'',
              }
            }
            var group = JSON.stringify(f(o));
            
            groups[group] = groups[group] || [];
            
            if(newuid==group){
              day=day+1;
            }
            groups[group].push(o);
            
             
          
           
            // groups[group].score=groups[group].length;
        });
        if(day>0){
          var nickName=wx.getStorageSync('nickName');
          var avatarurl=wx.getStorageSync('uimg')
          wx.setStorageSync('day', day)
        that.setData({
          day:day,
          userInfo:{day:day,nickName:nickName,avatarurl:avatarurl}
        })
      }
        
        return Object.keys(groups).map(function (group) {
            return groups[group];
        }); 
    },
    getAllList: function() {
        var that=this;
        const query = wx.Bmob.Query("vote_answer");
       
    
        query.statTo("groupby", "uid");
        query.statTo("groupcount", "true");
        query.statTo("having",{"_count":{"$gt":20}});
        query.statTo("order", "_count");
     
        query.find().then(res => {
       
        
        });
      
      
    },
    onShareAppMessage: function(t) {
        return  {
            title: "最佳辩手排行榜,讨论热点话题~",
            path: "/pages/index/index"
        };
    },
    onPullDownRefresh: function() {
    
   
    }
});